<template>
  <page-header-wrapper
    title="照片研判"
    content="无人机在配送过程中会自动拍摄起飞、途中和降落照片，您可以通过这些照片判断订单的完成情况。"
  >
    <div class="table-page-search-wrapper">
      <a-form layout="inline">
        <a-row :gutter="48">
          <a-col :md="8" :sm="24">
            <a-form-item label="订单编号">
              <a-input v-model="queryParam.orderSn" placeholder="请输入订单编号"/>
            </a-form-item>
          </a-col>
          <a-col :md="8" :sm="24">
            <a-form-item label="照片类型">
              <a-select v-model="queryParam.photoType" placeholder="请选择" default-value="">
                <a-select-option value="">全部</a-select-option>
                <a-select-option value="takeoff">起飞照片</a-select-option>
                <a-select-option value="transit">途中照片</a-select-option>
                <a-select-option value="landing">降落照片</a-select-option>
              </a-select>
            </a-form-item>
          </a-col>
          <a-col :md="8" :sm="24">
            <a-form-item label="拍摄时间">
              <a-range-picker v-model="queryParam.captureTime" style="width: 100%" />
            </a-form-item>
          </a-col>
        </a-row>
        <a-row>
          <a-col :span="24" style="text-align: right;">
            <a-button type="primary" @click="handleSearch">查询</a-button>
            <a-button style="margin-left: 8px" @click="handleReset">重置</a-button>
          </a-col>
        </a-row>
      </a-form>
    </div>

    <a-tabs v-model="currentTab" @change="handleTabChange">
      <a-tab-pane key="all" tab="全部照片"></a-tab-pane>
      <a-tab-pane key="pending" tab="待研判"></a-tab-pane>
      <a-tab-pane key="approved" tab="已通过"></a-tab-pane>
      <a-tab-pane key="rejected" tab="已拒绝"></a-tab-pane>
    </a-tabs>

    <a-list
      rowKey="id"
      :grid="{gutter: 24, lg: 3, md: 2, sm: 1, xs: 1}"
      :dataSource="filteredDataSource"
      :loading="loading"
      class="card-list"
    >
      <a-list-item slot="renderItem" slot-scope="item">
        <a-card :hoverable="true">
          <img
            slot="cover"
            :alt="item.title"
            :src="item.photoUrl"
            style="height: 200px; object-fit: cover;"
            @click="handlePreview(item)"
          />
          <a-card-meta>
            <a slot="title">{{ item.title }}</a>
            <div slot="description">
              <p class="meta-info">
                <a-icon type="shopping" /> 订单编号：{{ item.orderSn }}
              </p>
              <p class="meta-info">
                <a-icon type="camera" /> 照片类型：{{ getPhotoTypeText(item.photoType) }}
              </p>
              <p class="meta-info">
                <a-icon type="clock-circle" /> 拍摄时间：{{ item.captureTime }}
              </p>
              <p class="meta-info">
                <a-icon type="environment" /> 拍摄位置：{{ item.location }}
              </p>
              <p class="meta-info">
                <a-icon type="robot" /> 无人机ID：{{ item.droneId }}
              </p>
              <p class="meta-status">
                <a-tag :color="getStatusColor(item.status)">{{ getStatusText(item.status) }}</a-tag>
              </p>
            </div>
          </a-card-meta>
          <template slot="actions">
            <a @click="handlePreview(item)">查看</a>
            <a-dropdown v-if="item.status === 'pending'">
              <a class="ant-dropdown-link" @click="e => e.preventDefault()">
                研判 <a-icon type="down" />
              </a>
              <a-menu slot="overlay">
                <a-menu-item key="1" @click="handleApprove(item)">
                  <a-icon type="check-circle" style="color: #52c41a" /> 通过
                </a-menu-item>
                <a-menu-item key="2" @click="handleReject(item)">
                  <a-icon type="close-circle" style="color: #f5222d" /> 拒绝
                </a-menu-item>
              </a-menu>
            </a-dropdown>
            <a v-else-if="item.status === 'approved'" @click="handleReject(item)">拒绝</a>
            <a v-else @click="handleApprove(item)">通过</a>
          </template>
        </a-card>
      </a-list-item>
    </a-list>

    <a-modal
      :visible="previewVisible"
      :footer="null"
      @cancel="previewVisible = false"
      width="800px"
    >
      <img :alt="previewItem.title" style="width: 100%" :src="previewItem.photoUrl" />
      <div style="margin-top: 16px;">
        <h3>{{ previewItem.title }}</h3>
        <p><strong>订单编号：</strong>{{ previewItem.orderSn }}</p>
        <p><strong>照片类型：</strong>{{ getPhotoTypeText(previewItem.photoType) }}</p>
        <p><strong>拍摄时间：</strong>{{ previewItem.captureTime }}</p>
        <p><strong>拍摄位置：</strong>{{ previewItem.location }}</p>
        <p><strong>无人机ID：</strong>{{ previewItem.droneId }}</p>
        <p><strong>状态：</strong><a-tag :color="getStatusColor(previewItem.status)">{{ getStatusText(previewItem.status) }}</a-tag></p>
        <p v-if="previewItem.comment"><strong>研判备注：</strong>{{ previewItem.comment }}</p>

        <div v-if="previewItem.status === 'pending'" style="margin-top: 16px;">
          <a-textarea
            v-model="judgmentComment"
            placeholder="请输入研判备注"
            :rows="3"
            style="margin-bottom: 16px;"
          />
          <a-button type="primary" @click="handleApproveWithComment(previewItem)">通过</a-button>
          <a-button type="danger" style="margin-left: 8px;" @click="handleRejectWithComment(previewItem)">拒绝</a-button>
        </div>
      </div>
    </a-modal>
  </page-header-wrapper>
</template>

<script>
import moment from 'moment'

export default {
  name: 'PhotoJudgment',
  data () {
    return {
      loading: true,
      currentTab: 'all',
      queryParam: {
        orderSn: '',
        photoType: '',
        captureTime: []
      },
      dataSource: [],
      previewVisible: false,
      previewItem: {},
      judgmentComment: ''
    }
  },
  computed: {
    filteredDataSource () {
      let result = [...this.dataSource]

      // 根据标签筛选
      if (this.currentTab !== 'all') {
        result = result.filter(item => item.status === this.currentTab)
      }

      // 根据查询条件筛选
      if (this.queryParam.orderSn) {
        result = result.filter(item => item.orderSn.includes(this.queryParam.orderSn))
      }

      if (this.queryParam.photoType) {
        result = result.filter(item => item.photoType === this.queryParam.photoType)
      }

      if (this.queryParam.captureTime && this.queryParam.captureTime.length === 2) {
        const startTime = this.queryParam.captureTime[0].valueOf()
        const endTime = this.queryParam.captureTime[1].valueOf()
        result = result.filter(item => {
          const itemTime = moment(item.captureTime).valueOf()
          return itemTime >= startTime && itemTime <= endTime
        })
      }

      return result
    }
  },
  mounted () {
    this.getList()
  },
  methods: {
    getList () {
      this.loading = true
      // 模拟API请求
      setTimeout(() => {
        this.dataSource = this.generateMockData(24)
        this.loading = false
      }, 500)
    },

    handleSearch () {
      this.getList()
    },

    handleReset () {
      this.queryParam = {
        orderSn: '',
        photoType: '',
        captureTime: []
      }
      this.getList()
    },

    handleTabChange (key) {
      this.currentTab = key
    },

    handlePreview (item) {
      this.previewItem = { ...item }
      this.judgmentComment = item.comment || ''
      this.previewVisible = true
    },

    handleApprove (item) {
      this.$confirm({
        title: '确认通过',
        content: `确定要通过订单 ${item.orderSn} 的${this.getPhotoTypeText(item.photoType)}吗？`,
        onOk: () => {
          // 模拟API请求
          const index = this.dataSource.findIndex(i => i.id === item.id)
          if (index !== -1) {
            this.dataSource[index] = {
              ...this.dataSource[index],
              status: 'approved',
              comment: ''
            }
            this.$message.success('已通过')
          }
        }
      })
    },

    handleReject (item) {
      this.$confirm({
        title: '确认拒绝',
        content: `确定要拒绝订单 ${item.orderSn} 的${this.getPhotoTypeText(item.photoType)}吗？`,
        onOk: () => {
          // 模拟API请求
          const index = this.dataSource.findIndex(i => i.id === item.id)
          if (index !== -1) {
            this.dataSource[index] = {
              ...this.dataSource[index],
              status: 'rejected',
              comment: ''
            }
            this.$message.success('已拒绝')
          }
        }
      })
    },

    handleApproveWithComment (item) {
      // 模拟API请求
      const index = this.dataSource.findIndex(i => i.id === item.id)
      if (index !== -1) {
        this.dataSource[index] = {
          ...this.dataSource[index],
          status: 'approved',
          comment: this.judgmentComment
        }
        this.$message.success('已通过')
        this.previewVisible = false
      }
    },

    handleRejectWithComment (item) {
      // 模拟API请求
      const index = this.dataSource.findIndex(i => i.id === item.id)
      if (index !== -1) {
        this.dataSource[index] = {
          ...this.dataSource[index],
          status: 'rejected',
          comment: this.judgmentComment
        }
        this.$message.success('已拒绝')
        this.previewVisible = false
      }
    },

    getPhotoTypeText (type) {
      const types = {
        takeoff: '起飞照片',
        transit: '途中照片',
        landing: '降落照片'
      }
      return types[type] || '未知类型'
    },

    getStatusText (status) {
      const statuses = {
        pending: '待研判',
        approved: '已通过',
        rejected: '已拒绝'
      }
      return statuses[status] || '未知状态'
    },

    getStatusColor (status) {
      const colors = {
        pending: 'orange',
        approved: 'green',
        rejected: 'red'
      }
      return colors[status] || 'default'
    },

    generateMockData (count) {
      const photoTypes = ['takeoff', 'transit', 'landing']
      const statuses = ['pending', 'approved', 'rejected']
      const statusWeights = [0.5, 0.3, 0.2] // 权重，使pending状态的数据更多

      return Array(count).fill().map((_, i) => {
        const id = i + 1
        const orderSn = `ORD${String(10000 + Math.floor(id / 3)).padStart(5, '0')}`
        const photoType = photoTypes[id % 3]
        const droneId = `DRONE-${String(100 + Math.floor(Math.random() * 50)).padStart(3, '0')}`

        // 根据权重随机选择状态
        let status
        const rand = Math.random()
        if (rand < statusWeights[0]) {
          status = statuses[0]
        } else if (rand < statusWeights[0] + statusWeights[1]) {
          status = statuses[1]
        } else {
          status = statuses[2]
        }

        // 随机生成拍摄时间，最近30天内
        const daysAgo = Math.floor(Math.random() * 30)
        const captureTime = moment().subtract(daysAgo, 'days')
                            .subtract(Math.floor(Math.random() * 24), 'hours')
                            .format('YYYY-MM-DD HH:mm:ss')

        // 随机生成位置
        const locations = [
          '北京市海淀区中关村',
          '上海市浦东新区张江高科技园区',
          '广州市天河区珠江新城',
          '深圳市南山区科技园',
          '杭州市西湖区'
        ]
        const location = locations[Math.floor(Math.random() * locations.length)]

        // 根据照片类型选择不同的示例图片
        let photoUrl
        if (photoType === 'takeoff') {
          photoUrl = `https://source.unsplash.com/400x300/?drone,takeoff,${id}`
        } else if (photoType === 'transit') {
          photoUrl = `https://source.unsplash.com/400x300/?aerial,view,${id}`
        } else {
          photoUrl = `https://source.unsplash.com/400x300/?landing,delivery,${id}`
        }

        return {
          id,
          orderSn,
          photoType,
          title: `${this.getPhotoTypeText(photoType)} #${id}`,
          photoUrl,
          captureTime,
          location,
          droneId,
          status,
          comment: status !== 'pending' ? (status === 'approved' ? '照片清晰，配送正常' : '照片模糊，无法确认配送状态') : ''
        }
      })
    }
  }
}
</script>

<style lang="less" scoped>
  @import "~@/components/index.less";

  .table-page-search-wrapper {
    margin-bottom: 16px;
  }

  .card-list {
    margin-top: 24px;

    :deep(.ant-card-cover) {
      cursor: pointer;
    }

    :deep(.ant-card-body:hover) {
      .ant-card-meta-title>a {
        color: @primary-color;
      }
    }

    :deep(.ant-card-meta-title) {
      margin-bottom: 12px;

      &>a {
        display: inline-block;
        max-width: 100%;
        color: rgba(0,0,0,.85);
      }
    }

    .meta-info {
      margin-bottom: 8px;
      color: rgba(0, 0, 0, 0.65);
    }

    .meta-status {
      margin-top: 12px;
    }
  }
</style>
